package ext.tianma.project.relatedproduct;

import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;

import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.iba.value.DefaultAttributeContainer;
import wt.iba.value.IBAHolder;
import wt.iba.value.litevalue.AbstractValueView;
import wt.iba.value.service.IBAValueHelper;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.projmgmt.admin.Project2;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.vc.Iterated;
import wt.vc.VersionControlHelper;
import ext.com.iba.IBAUtil;
import ext.tianma.bom.workflow.ExamineAndApproveConfirmBusiness;
import ext.tianma.version.ComToolUtil;

/**Description:【项目和成品属性关联】时所用到的业务逻辑
 * @author    :  YangWen
 * @create at :  2013-8-19   上午10:25:52
 */
public class CreateProjectBusiness {
	
	private static boolean isShow = true;
	
	/**
	 * 静态构造函数，防止实例化
	 */
	private CreateProjectBusiness(){
		
	}
	
	/**输出log信息
	 * @param info
	 */
	private static void out(String info){
		if(isShow)
			System.out.println("项目和成品属性关联:"+CreateProjectBusiness.class.getName()+":"+info);
	}
	
	
	/**通过产品编号获取其所对应的最新版本的成品
	 * @param ConsumptionRFQName
	 * @return
	 */
	public static WTDocument getLatestDocument(String ConsumptionRFQName){
		
		if(ComToolUtil.isEmpty(ConsumptionRFQName))
			return null;
		
		WTDocumentMaster master = null;
		try {
			master = getWTDocumentMasterByName(ConsumptionRFQName);
		} catch (WTException e) {
			e.printStackTrace();
		}
		WTDocument  doc = null;
		try {
			doc = getLatestWTDocumentByMaster(master);
		} catch (WTException e) {
			e.printStackTrace();
		}
		
		
		try {
			if(!ExamineAndApproveConfirmBusiness.isObjectType(doc, ".ConsumptionRFQ"))
				doc = null;
		} catch (WTException e) {
			e.printStackTrace();
			doc = null;
		}
		
		if(ComToolUtil.isEmpty(doc)){
			out("不存在名称为【"+ConsumptionRFQName+"】的消费类RFQ文档，直接退出！");
			return null;
		}
				
				
		return doc;
	}
	
	
	
    public static WTDocumentMaster getWTDocumentMasterByName(String docName) throws WTException {
        WTDocumentMaster master = null;
        QuerySpec qs = null;
        QueryResult qr = null;
        qs = new QuerySpec(WTDocumentMaster.class);
        SearchCondition sc = new SearchCondition(WTDocumentMaster.class, "name", "=", docName);
        qs.appendSearchCondition(sc);
        qr = PersistenceHelper.manager.find(qs);
        if(qr.hasMoreElements())
            master = (WTDocumentMaster)qr.nextElement();
        return master;
}
	 
		/** YW
		 * 从master中获取最新的文档 
		 * @param master WTDocumentMaster对象
		 * @return 最新的文档对象
		 * @throws WTException
		 */
		public static WTDocument getLatestWTDocumentByMaster(WTDocumentMaster master)  throws WTException  {
		        if(master == null)
		            return null;
		        Iterated iterated = null;
		        QueryResult queryresult = VersionControlHelper.service.allIterationsOf(master);
		        while(queryresult.hasMoreElements()){
		            iterated = (Iterated)queryresult.nextElement();
		            if(iterated.isLatestIteration())
		            	break;
		        }
		        return (WTDocument)iterated;
		  }

	/**获得从【成品】中设置给【项目】的IBA属性
	 * @return HashMap<String , String>对象  <成品IBA属性名称，项目IBA属性名称>
	 */
	public static HashMap<String , String> getDocAndProjectAttribute(){
		
		//<成品IBA属性名称，项目IBA属性名称>
		HashMap<String , String> result = new HashMap<String, String>();
				
		//分辨率（横*竖）  
		result.put("finishedGoodResolution", "finishedGoodResolution");

		//产品型号    
		result.put("productType", "productType");

		//产品尺寸inch      
		result.put("finishedGoodSize", "finishedGoodSize");

		//panel研发地
		result.put("panelDevelopedLand", "panelDevelopedLand");

		//Panel产地
		result.put("panelPlaceOfOrigin", "panelPlaceOfOrigin");

		//产地NPI/NTI  
		result.put("PlaceOfOrigin", "PlaceOfOrigin");

		//RFQ时间【时间类型】
		result.put("RFQTime", "RFQTime");

		//显示模式  
		result.put("finishedGoodDisplayMode", "ProductType2");

		//产品用途 
		result.put("finishedGoodUse", "finishedGoodUse");

		
		
		return result;		
	}
	
	
	/**设置属性
	 * @param project Project2对象
	 * @param ht  Hashtable<String , Object>对象，即某个消费类RFQ对象的所有属性
	 * @return 
	 */
	public static boolean setAttribution(Project2 project , Hashtable<String , Object> ht){
		
		if(ComToolUtil.isEmpty(project) || ht == null || ht.size() == 0)
			return false;
		
		//【项目】类型里要设置的属性
		Hashtable<String , Object> projectAttribute = new Hashtable<String, Object>();
		HashMap<String , String> map = getDocAndProjectAttribute();		
		
		for(Iterator<String> itr = ht.keySet().iterator(); itr.hasNext();){ 
			String productStr = (String) itr.next(); 
			Object productValue = ht.get(productStr); 
			out(productStr+"--"+productValue); 
						
			for(Iterator<String> secondIterator = map.keySet().iterator(); secondIterator.hasNext();){ 
				String productKey = (String) secondIterator.next(); 
				String projectStr = (String)map.get(productKey); 
				out(productKey+"--"+projectStr); 
				
				if(ComToolUtil.isEmpty(productKey)||ComToolUtil.isEmpty(projectStr))
					continue;
				
				if(productStr.equals(productKey)){
					projectAttribute.put(projectStr, productValue);
				}				
			}			
		} 
		
		try {			
			IBAUtil.forceSetIBAValues(project, projectAttribute);
			return true;
		} catch (WTException e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	
	/**设置属性
	 * @param project 消费项目对象
	 * @param ConsumptionRFQName  消费类RFQ对象的名称
	 * @return boolean 如果设置属性成功，则返回true
	 */
	public static boolean setAttribution(Project2 project , String ConsumptionRFQName){
		
		if(ComToolUtil.isEmpty(project) || ComToolUtil.isEmpty(ConsumptionRFQName))
			return false;
		
		WTDocument doc = getLatestDocument(ConsumptionRFQName);
		
		/*//产品型号,项目名称(即成品的编号)
		Hashtable<String , Object> projectAttribute = new Hashtable<String, Object>();
		projectAttribute.put("finishedGoodType" , doc.getNumber());
		try {
			IBAUtil.forceSetIBAValues(project,projectAttribute); 
		} catch (WTException e1) {
			e1.printStackTrace();
		}*/
				
		Hashtable<String , Object> ht = null;
		
		try {
			 ht = getIBAValues(doc);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
		
		if(ht == null || ht.size() == 0)
			return false;
				
		return setAttribution(project,ht);
	}
	
	
	/** 从master中获取最新的部件 
	 * @param master WTPartMaster对象
	 * @return 最新的部件对象
	 * @throws WTException
	 */
	public static WTPart getLatestWTPartByMaster(WTPartMaster master)  throws WTException  {
	        if(master == null)
	            return null;
	        Iterated iterated = null;
	        QueryResult queryresult = VersionControlHelper.service.allIterationsOf(master);
	        while(queryresult.hasMoreElements()){
	            iterated = (Iterated)queryresult.nextElement();
	            if(iterated.isLatestIteration())
	            	break;
	        }
	        return (WTPart)iterated;
	  }
	  
		/**YW
		 * 获取指定对象的所有属性值列表
		 * @param ibaHolder IBAHolder对象，例如文档、零部件、图档等
		 * @return Hashtable<String , Object> 
		 * @throws WTException 获取指定对象的所有属性值列表时失败！
		 * @throws java.rmi.RemoteException 获取指定对象的所有属性值列表时失败！
		 */
		public static Hashtable<String , Object> getIBAValues(IBAHolder ibaHolder) throws WTException, java.rmi.RemoteException {
			
			ibaHolder = IBAValueHelper.service.refreshAttributeContainerWithoutConstraints(ibaHolder);
			DefaultAttributeContainer dac = (DefaultAttributeContainer) ibaHolder.getAttributeContainer();
			AbstractValueView valueViews[] = dac.getAttributeValues();

			Hashtable<String , Object> result = new Hashtable<String , Object>();

			for (int j = 0; j < valueViews.length; j++) {
				AbstractValueView avv = valueViews[j];                        
				Object value = IBAUtil.getInternalValue(avv);
				if (value != null)
					result.put(avv.getDefinition().getLogicalIdentifier(), value);
			}
			
			return result;
		}
	
}
